package com.houger.ddd.advice;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.houger.ddd.common.utils.R;
import com.houger.ddd.common.utils.StatusCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.ibatis.annotations.Case;
import org.springframework.stereotype.Component;
 

 
@Component
public class SentinelBlockHandler implements BlockExceptionHandler {
 
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        // 设置编码为JSON格式
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        // 定义返回的JSON数据结构
        JSONObject json = new JSONObject();
        switch (e){
            case FlowException f -> {
                json.put("code", StatusCode.RESP_CODE_FLOW_LIMITING_EXCEPTION.getCode());
                json.put("message", StatusCode.RESP_CODE_FLOW_LIMITING_EXCEPTION.getMsg());
            }
            case DegradeException d ->{
                json.put("code", StatusCode.RESP_CODE_DEGRADE_EXCEPTION.getCode());
                json.put("message", StatusCode.RESP_CODE_DEGRADE_EXCEPTION.getMsg());
            }
            case SystemBlockException s ->{
                json.put("code", StatusCode.RESP_CODE_SYSTEM_BLOCK_EXCEPTION.getCode());
                json.put("message", StatusCode.RESP_CODE_SYSTEM_BLOCK_EXCEPTION.getMsg());
            }
            default -> {
                json.put("code", StatusCode.SERVICE_UNAVAILABLE.getCode());
                json.put("message", StatusCode.SERVICE_UNAVAILABLE.getMsg());
            }
        }
        // 将JSON数据写入到response中
        String jsonString = JSON.toJSONString(json);
        response.getWriter().write(jsonString);
    }
}